package flca.osm.perst.util;

import java.util.HashSet;
import java.util.Set;

import org.garret.perst.Rectangle;

import flca.osm.perst.model.IntersectRootClass;
import flca.osm.perst.model.PNode;
import flca.osm.perst.model.PNode;
import flca.osm.perst.model.PRootClass;
import flca.osm.perst.model.PWay;

public class FindIntersections {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		FindIntersections executor= new FindIntersections();
		executor.execute();
	}

	//---------------------------------------------
	
	private Set<Integer> refNodes = new HashSet<Integer>();

	public void execute() 
	{
		for (PWay way : getInputRoot().wayPk) {
			for (Integer ref : way.getWayNodes()) {
				processWayRef(ref);
			}
		}
		
		DbHelper.getInstance().cleanup();
		
		System.out.println("found " + getOutputRoot().spatialIdx.size() + " intersections");
	}

	private void processWayRef(Integer ref) {
		if (refNodes.contains(ref)) {
			PNode node = getInputRoot().nodePk.get(ref);
			PNode intersNode = new PNode(node.getId(), node.getLat(), node.getLon());
			Rectangle rect = new Rectangle(node.getLat(), node.getLon(), node.getLat(), node.getLon());
			getOutputRoot().spatialIdx.put(rect, intersNode);
		} else {
			refNodes.add(ref);
		}
	}
	
	private PRootClass getInputRoot() {
		return DbHelper.getInstance().getOsmRoot();
	}

	private IntersectRootClass getOutputRoot() {
		return DbHelper.getInstance().getInterSectRoot();
	}
}
